package com.lzh.intercepter;


import cn.hutool.json.JSONUtil;
import com.auth0.jwt.interfaces.Claim;
import com.lzh.constant.RedisKey;
import com.lzh.utils.JwtUtils;
import com.lzh.utils.RedisUtils;
import com.lzh.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;


//优先级越小拦截器优先级越高
@Order(-1)
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    public static final String TOKEN = "token";

    public static final String TOKEN_SCHEMA = "Bearer ";


    @Resource
    private JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        Long validUid = getValidUid(token);
        if(Objects.nonNull(validUid)){
            //request.setAttribute(TOKEN_SCHEMA,)
            //可以优化使用threadLocal
            return true;
        }else{
            //沒有token又不是登录的公开接口则返回
            if(!isPublicPath(request.getRequestURI())){
                response.setStatus(401);
                ResponseResult.error(401, "token失效");
                response.setContentType("application/json");
                response.getWriter().write(JSONUtil.toJsonStr(ResponseResult.error(401, "token失效")));
                return false;

            }
        }
        return true;
    }


    private boolean isPublicPath(String path){
        String[] split = path.split("/");
        return split.length > 2 && "public".equals(split[0]);
    }

    private Long getValidUid(String  token) {
        boolean verify = verify(token);
        return verify ? jwtUtils.getUidOrNull(token) : null;
    }

    private boolean verify(String token){
        Long uidOrNull = jwtUtils.getUidOrNull(token);
        if(Objects.isNull(token)){
            return false;
        }
        String redisKey = RedisKey.getKey(RedisKey.USER_TOKEN, uidOrNull);
        String realToken = RedisUtils.getStr(redisKey);
        return Objects.equals(realToken, token);
    }


    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN);
        return Optional.ofNullable(token).filter(t -> t.startsWith(TOKEN_SCHEMA))
                .map(t -> t.substring(TOKEN_SCHEMA.length()))
                .orElse(null);
    }
}
